package com.lei.sandbox.controller;

import com.lei.sandbox.PythonDockerCodeSandbox;
import com.lei.sandbox.JavaDockerCodeSandbox;
import com.lei.sandbox.model.ExecuteCodeRequest;
import com.lei.sandbox.CppDockerCodeSandbox;
import com.lei.sandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {

    //定义请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTU_REQUEST_SECRET = "leirui";

    @Resource
    private PythonDockerCodeSandbox pythonDockerCodeSandbox;

    @Resource
    private JavaDockerCodeSandbox javaDockerCodeSandbox;

    @Resource
    private CppDockerCodeSandbox cppDockerCodeSandbox;


    @GetMapping("/hello")
    public String hello(){
        return "ok";
    }

    /**
     * 执行代码
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request , HttpServletResponse response) {
        //基本认证
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if(!AUTU_REQUEST_SECRET.equals(authHeader)){
            response.setStatus(403);
            return null;
        }
        if(executeCodeRequest == null){
            throw new RuntimeException("请求参数为空");
        }
        String language = executeCodeRequest.getLanguage();
        if("python".equals(language)){
            return pythonDockerCodeSandbox.executeCode(executeCodeRequest);
        }
        if("java".equals(language)){
            return javaDockerCodeSandbox.executeCode(executeCodeRequest);
        }
        if ("cpp".equals(language) || "c".equals(language)) {
            return cppDockerCodeSandbox.executeCode(executeCodeRequest);
        }
        throw new RuntimeException("不支持的语言: " + language);
    }
}